package com.lzh.dlykserver.controller;

import com.alibaba.excel.EasyExcel;
import com.github.pagehelper.PageInfo;
import com.lzh.dlykserver.entity.TTran;
import com.lzh.dlykserver.entity.TTranRemark;
import com.lzh.dlykserver.query.TranDTO;
import com.lzh.dlykserver.query.TranQuery;
import com.lzh.dlykserver.query.TransactionQuery;
import com.lzh.dlykserver.result.R;
import com.lzh.dlykserver.result.TransactionExcel;
import com.lzh.dlykserver.service.TransactionRemarkService;
import com.lzh.dlykserver.service.TransactionService;
import lombok.RequiredArgsConstructor;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@RestController
@RequiredArgsConstructor
@RequestMapping("/api")
public class TransactionController {

    private final TransactionService transactionService;
    private final TransactionRemarkService transactionRemarkService;

    /**
     * 市场活动分页
     * @param current
     * @return
     */
    @GetMapping("transactions")
    public R activityPage(@RequestParam(value = "current", required = false) Integer current,
                          TransactionQuery tranQuery) {
        if (current == null) {
            current = 1;
        }
        PageInfo<TTran> pageInfo = transactionService.getTranByPage(current, tranQuery);
        return R.OK(pageInfo);
    }

    /**
     * 查询交易详情接口
     */
    @GetMapping("/transaction/detail/{id}")
    public R getTransactionDetail(@PathVariable("id") Integer id) {
        TTran tran = transactionService.getTransactionById(id);
        if (tran != null) {
            return R.OK(tran);
        }
        return R.FAIL("未找到该交易记录");
    }

    /**
     * 添加交易备注
     * @param transactionQuery
     * @param toklen
     * @return
     */
    @PostMapping("/transaction/remark")
    public R addTransactionRemark(@RequestBody TransactionQuery transactionQuery,
                                  @RequestHeader("Authorization") String toklen) {
        transactionQuery.setToken(toklen);
        int i = transactionService.saveTransactionRemark(transactionQuery);
        if (i > 0) {
            return R.OK();
        }
        return R.FAIL("添加失败");
    }

    /**
     * 交易备注分页
     * @param current
     * @param tranId
     * @return
     */
    @GetMapping("/transaction/remark")
    public R tranRemarkPage(@RequestParam(value = "current", required = false) Integer current,
                            @RequestParam("tranId") Integer tranId) {
        TranQuery tranQuery = new TranQuery();
        tranQuery.setTranId(tranId);
        if (current == null) {
            current = 1;
        }
        PageInfo<TTranRemark> pageInfo = transactionRemarkService.getClueRemarkByPage(current, tranQuery);
        return R.OK(pageInfo);
    }

    /**
     * 编辑交易备注
     * @param id
     * @return
     */
    @GetMapping("/transaction/remark/{id}")
    public R getEditedTransactionRemark(@PathVariable("id") Integer id) {
        TTranRemark tranRemark = transactionRemarkService.getTranRemarkById(id);
        if (tranRemark != null) {
            return R.OK(tranRemark);
        }
        return R.FAIL("未找到该交易备注");
    }

    /**
     * 修改交易备注
     * @param transactionQuery
     * @param toklen
     * @return
     */
    @PutMapping("/transaction/remark/update")
    public R editTransactionRemark(@RequestBody TransactionQuery transactionQuery,
                                   @RequestHeader("Authorization") String toklen) {
        transactionQuery.setToken(toklen);
        int i = transactionRemarkService.updateTransactionRemark(transactionQuery);
        return i >= 1 ? R.OK() : R.FAIL();
    }

    /**
     * 删除交易备注
     * @param id
     * @return
     */
    @DeleteMapping("/transaction/remark/delete/{id}")
    public R delTransactionMark(@PathVariable("id") Integer id) {
        int i = transactionRemarkService.delClueMark(id);
        if (i > 0) {
            return R.OK();
        }
        return R.FAIL("删除失败");
    }

    @PutMapping("/transaction/edit")
    public R updateTransaction(@RequestBody TranDTO transactionQuery,
                               @RequestHeader("Authorization") String toklen) {
        transactionQuery.setToken(toklen);
        int i = transactionService.updateTransaction(transactionQuery);
        return i >= 1 ? R.OK() : R.FAIL();
    }

    /**
     * 导出Excel
     * @param response
     * @param ids
     * @throws IOException
     */
    @GetMapping("/transaction/exportExcel")
    public void exportExcel(HttpServletResponse response,
                            @RequestParam(value = "ids", required = false) String ids) throws IOException {
        // 设置响应头，告知浏览器下载文件
        response.setContentType("application/octet-stream");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-disposition", "attachment;filename="
                + URLEncoder.encode("交易数据" + System.currentTimeMillis(), "utf-8")
                + ".xlsx");

        // 将id列表转换为List
        List<String> idList = StringUtils.hasText(ids) ? new ArrayList<>(Arrays.asList(ids.split(","))) : new ArrayList<>();

        // 从数据库获取交易数据
        List<TransactionExcel> list = transactionService.getTransactionByExcel(idList);

        // 使用EasyExcel将数据写入响应的输出流
        EasyExcel.write(response.getOutputStream(), TransactionExcel.class)
                .sheet("Transactions")
                .doWrite(list);
    }

}
